package com.cxh.supermarket.common.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.math.BigDecimal;

@Configuration
public class BigDecimalSerializer extends JsonSerializer<BigDecimal> {

    @Override
    public void serialize(BigDecimal value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        String removeZeroValue = this.removeZero(value.toPlainString());
        jsonGenerator.writeString(removeZeroValue);
    }

    private String removeZero(String removeZeroValue) {
        if (removeZeroValue.contains(".")) {
            String end = removeZeroValue.substring(removeZeroValue.length() - 1);
            if (end.equals("0")) {
                removeZeroValue = removeZeroValue.substring(0, removeZeroValue.length() - 1);
                removeZeroValue = this.removeZero(removeZeroValue);
            } else if (end.equals(".")) {
                removeZeroValue = removeZeroValue.substring(0, removeZeroValue.length() - 1);
            }
        }
        return removeZeroValue;
    }
}
